/**
 *
*/
package com.bbcare.util.nullCheck;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.bbcare.comm.AppException;
import com.bbcare.comm.Constants;
import com.bbcare.comm.ErrorCode;
import com.bbcare.util.FieldNotNull;
import com.bbcare.util.FieldNotNullCheck;

/**
 * @Description: TODO
 * @author MLi
 * @date 2018年4月9日
 * @version V1.0
 * @param <T>
 */
public class ListNull<T> extends ObjectNull {

	@SuppressWarnings("unchecked")
	@Override
	public void isNullCheck(Method method, Object obj, FieldNotNull fieldNotNull, String nestFieldName) {
		List<T> result = null;
		try {
			result = (List<T>) method.invoke(obj);
		} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			e.printStackTrace();
		}
		if(result == null || result.size() == 0){
			try{
				throw (new AppException(ErrorCode.DISTREAT_EXCEPTION_TYPE_INPUT_DATA_VERIFY_ERROR,
                    Constants.API_INPUT_PARAMS_DATA_ERROR + "，" + fieldNotNull.desc() + "为空！"));
			} catch (AppException e) {
				throw(e);
			}
		} else {
			String fieldNameStr = nestFieldName.substring(nestFieldName.indexOf(":")+2, nestFieldName.length()-1);
			//拆分{}
			String[] notNullFieldNames = null;
			String nestStr = null;
			if(fieldNameStr.indexOf("{") != -1 && fieldNameStr.indexOf("}") != -1){
				String beforeStr = fieldNameStr.substring(0, fieldNameStr.indexOf("{"));
				beforeStr = beforeStr.substring(0, beforeStr.lastIndexOf(","));
				String behindStr = fieldNameStr.substring(fieldNameStr.lastIndexOf("}") + 1);
				nestStr = fieldNameStr.substring(fieldNameStr.indexOf(beforeStr) + beforeStr.length() + 1,
						fieldNameStr.indexOf("}") + 1);
				notNullFieldNames = (beforeStr + behindStr).split(",");
			} else {
				notNullFieldNames = fieldNameStr.split(",");
			}
			for (T t : result) {
				FieldNotNullCheck.fieldNotNullValid(t, add(notNullFieldNames, nestStr));
			}
		}
	}
	
	/**
	 * 扩容
	 * @param notNullFieldNames
	 */
	private static String[] add(String[] notNullFieldNames, String fieldName){
		if(StringUtils.isNotBlank(fieldName)){
			String[] notNullFieldNames_new = new String[notNullFieldNames.length+1];
			int i = 0;
			for(String fieldName2 : notNullFieldNames){
				notNullFieldNames_new[i++] = fieldName2;
			}
			notNullFieldNames_new[i] = fieldName;
			return notNullFieldNames_new;
		} else {
			return notNullFieldNames;
		}
	}

}
